//
//  MediaKeysApplication.m
//  MediaKeysPlugin
//
//  Created by Aaron Zinman on 7/25/09.
//  This file is part of MediaKeysPlugin.
//
//  MediaKeysPlugin is free software: you can redistribute it and/or modify
//  it under the terms of the GNU Lesser General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  any later version.
//
//  MediaKeysPlugin is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with MediaKeysPlugin.  If not, see <http://www.gnu.org/licenses/>.
//
//  Technique lifted from http://www.rogueamoeba.com/utm/2007/09/29/apple-keyboard-media-key-event-handling/

#import "MediaKeysApplication.h"
#import <IOKit/hidsystem/ev_keymap.h>
#import "MediaKeysPlugIn.h"

@implementation NSApplication (MediaKeysApplication)

- (void) mediaKeyEvent: (int)key state: (BOOL)state repeat: (BOOL)repeat {
	switch( key )	{
		case NX_KEYTYPE_PLAY:
			if( state == 0 ) {
        //Play pressed and released
        [[MediaKeysPlugIn sharedInstance] sendPlay];
      }
      break;
      
		case NX_KEYTYPE_FAST:
			if( state == 0 ) {
        //Next pressed and released
        [[MediaKeysPlugIn sharedInstance] sendForward];
      }
      break;
      
		case NX_KEYTYPE_REWIND:
			if( state == 0 ) {
        [[MediaKeysPlugIn sharedInstance] sendBackward];
      }
      break;
	}
}

- (void) interceptedSendEvent: (NSEvent*)event {
	if( [event type] == NSSystemDefined && [event subtype] == 8 )	{
		int keyCode = (([event data1] & 0xFFFF0000) >> 16);
		int keyFlags = ([event data1] & 0x0000FFFF);
		int keyState = (((keyFlags & 0xFF00) >> 8)) ==0xA;
		int keyRepeat = (keyFlags & 0x1);
		
		[self mediaKeyEvent: keyCode state: keyState repeat: keyRepeat];
  }
  // This will call the original sendEvent
  [self interceptedSendEvent:event];
}

@end
